package cn.csq.rpc.client;

import cn.csq.rpc.code.Decoder;
import cn.csq.rpc.code.Encoder;
import com.csq.rpc.common.utils.ReflectionUtils;

import java.lang.reflect.Proxy;

/**
 * @author csq
 * @version 1.0.0
 * @ClassName RpcClient.java
 * @Description PRC客户端
 * @createTime 2021年12月20日 23:16:00
 */
public class RpcClient {

    private RpcClientConfig rpcClientConfig;

    private Encoder encoder;

    private Decoder decoder;

    private TransportSelector selector;


    public RpcClient() {
        this(new RpcClientConfig());
    }

    public RpcClient(RpcClientConfig rpcClientConfig) {
        this.rpcClientConfig = rpcClientConfig;
        try {
            this.encoder = ReflectionUtils.newInstance(rpcClientConfig.getEncoderClass());
            this.decoder = ReflectionUtils.newInstance(rpcClientConfig.getDecoderClass());
            this.selector = ReflectionUtils.newInstance(rpcClientConfig.getSelectorClass());
            this.selector.init(
                    this.rpcClientConfig.getServers(),
                    this.rpcClientConfig.getConnectCount(),
                    this.rpcClientConfig.getTransportClass()
            );
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public Object getProxy(Class clazz) {
        return Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class[]{clazz},
                new RemoteInvoker(clazz,encoder,decoder,selector));
    }
}
